import md5 from "md5";
import Talk from '../controller/talk';
import Login from '../controller/login';
import MakeClientMsgPackage from '../controller/makeTemporaryTalk'
import Heartbeat from '../controller/heartbeat';
import TalkObject from './talkObject';
import { Sendcontroller } from "./sendController";
const sendController = new Sendcontroller();
const talkObject = new TalkObject();
import GetTalkDetail from '../controller/getTalkDetail';
const messageObject = {
    talk: new Talk(),
    login: new Login(),
    makeTemporaryTalk: new MakeClientMsgPackage(),
    heartbeat: new Heartbeat(),
    getTalkDetail: new GetTalkDetail(),
}
export class ReceiverController {
    constructor(so) {
        this.so = so;
    }
    /*服务器收到消息*/
    receiverMsg(msg) {
        console.log("接受到消息时间:", test());
        //1.收到消息发送回执
        if (!this.memberId) { console.log('未登录！memberId 为0！') }
        messageObject[msg.head.action].getMsg(msg);
        var serverMsg = { head: { po: 2, ms: 2, severMsgId: msg.head.serverMsgId, fromMemberId: this.memberId, action: '' }, body: { code: 200, data: '成功' } }
        const md5String = md5(JSON.stringify(serverMsg) + Date.now());
        serverMsg["head"]["clientMsgId"] = this.memberId + "_" + md5String;
        this.so.send(JSON.stringify(serverMsg));
        //2.被创建者不存在会话列表，判断是否需要重新获取会话列表
        talkObject.addChat(msg.body.talk_id, msg, () => {
            const fetchTalkDetailsMessage = sendController.pushMessage('getTalkDetail',
                { talk_id: msg.body.talk_id }, talkObject.member_id);
            sendController.sendReceiverMsg(fetchTalkDetailsMessage.data);
        });
    }
    /*接收member_id*/
    setMemberId(memberId) {
        this.memberId = memberId
    }
}

function test() {
    var now = new Date();
    var str,
        second = now.getSeconds(),
        minSecond = (Date.now() + '').slice(-3);
    str = second + '.' + minSecond;
    return str;
}



